package com.ts.proj.json;


import com.ts.base.controller.BaseController;
import com.ts.common.constant.InsUpdDelFlagConstant;
import com.ts.proj.entity.FileEntity;
import com.ts.proj.entity.FinanceEntity;
import com.ts.proj.entity.excelEntity.FinanceEntityExcel;
import com.ts.proj.entity.SystemUserEntity;
import com.ts.proj.service.FileService;
import com.ts.proj.service.FinanceService;
import com.ts.common.constant.ConsoleConstant;
import com.ts.util.PageData;
import com.ts.util.StringsUtil;
import com.ts.util.DateUtil;
import com.ts.util.EasyPoiUtil;
import com.ts.util.EntityAttributeUtil;
import com.ts.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;



import javax.servlet.http.HttpSession;
import com.ts.util.JsonUtils;

//说明 字符串：Finance，作为替换字符串 LOWERFinance

@RestController
public class FinanceJson extends BaseController{

    @Autowired
    private FinanceService financeService;

    @Autowired
    private FileService fileService;

    @Value("${upload.location-pre}")
    private String locaionPre ;

    @Value("${upload.split}")
    private String split;

    /**
     * 显示list
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "/finance-list/{page}/{size}/{id}")
    public Map<String,Object> financeList(@PathVariable("page") Integer page, @PathVariable("size") Integer size,@PathVariable("id") Integer id){
	
		HttpSession session = this.getRequest().getSession();
        SystemUserEntity user = JsonUtils.jsonToObject(session.getAttribute(ConsoleConstant.SESSIONUSER).toString(),SystemUserEntity.class);
	
        PageData pageData = this.getPageData();
        pageData.put("deleteFlag", "N");
		
		//用户权限
        if(user.getPowerLevel().equals("0")){
            pageData.put("userId", user.getId());
        }
        //如果是财务报告，查询收入为0，非财务报告查询收入非0，全选则不添加条件
        if(null!=pageData.get("selectValue")&&!"".equals(pageData.get("selectValue").toString())){
            pageData.put("selectValue", pageData.get("selectValue"));
        }

        pageData.put("belongTo", user.getBelongTo());
        pageData.put("proID", id);

        long count = financeService.count(pageData);
        List<FinanceEntity> finances = financeService.findAll(pageData,page-1,size);
        pageData.put("total",count);
        pageData.put("rows", finances);
        return pageData;
    }

    /**
     * 常量增删改
     * @return
     */
    @RequestMapping(value = "/finance-ins-upd-del/{id}")
    public Object logCreateUpdate(@PathVariable("id") String id){ 
	
		FinanceEntity finance = financeService.findById(Integer.valueOf(id));
        PageData pageData = this.getPageData();

        List<String> strings = EntityAttributeUtil.entityAttribute(FinanceEntity.class);
		 SystemUserEntity systemUserEntity = JsonUtils.jsonToObject(this.getRequest().getSession().getAttribute(ConsoleConstant.SESSIONUSER).toString(),SystemUserEntity.class);

        for(String attr :strings){
            //字段信息维护
            if(null!=pageData.get(attr)&&!"".equals(pageData.get(attr).toString())){
                //目前只能手动添加，这里添加所需要增加和修改的字段
                try {
                    Method[] methods = FinanceEntity.class.getDeclaredMethods();
                    for(int i=0;i<methods.length;i++){
                        Method method = methods[i];
                        Class<?>[] returnType = method.getParameterTypes();
                        if(method.getName().contains(StringsUtil.upperCase(attr))&&!method.getName().contains("get")){
                            if (returnType[0].getName().equals("java.lang.Integer")){
                                method.invoke(finance, Integer.valueOf(pageData.getString(attr)));
                            }
                            else{
                                method.invoke(finance, pageData.getString(attr));
                            }
                        }
						if(method.getName().equals("setUserId")){
                            finance.setUserId(systemUserEntity.getId());
                        }
                        if(method.getName().equals("setBelongTo")){
                            finance.setBelongTo(systemUserEntity.getBelongTo());
                        }
						if(method.getName().equals("setPowerLevel")){
                            finance.setPowerLevel(systemUserEntity.getPowerLevel());
                        }
                    }

                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }  catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
        //如果收入为0   是财务报告
        if(null!=pageData.get("assignMoney")&&"0".equals(pageData.get("assignMoney").toString())){
            finance.setYesOrNofinanceReport("0");
        }else {
            finance.setYesOrNofinanceReport("1");
        }
        //删除财务信息以及该信息下的文件（根据docType）
        if(null!=pageData.get("deleteFlag")&&!"".equals(pageData.get("deleteFlag").toString())){
            //1、根据doc_type可以查出所有相关联file（th_zt_meet_[meetid]）
            PageData pageData1 = new PageData();
            pageData1.put("deleteFlag", "N");
            pageData1.put("docType", "th_zt_finance_"+finance.getId());
            List<FileEntity> fileEntityList = fileService.findAll(pageData1);
            //遍历文件，删除
            for(FileEntity fileEntity : fileEntityList) {
                String path = locaionPre;
                path += fileEntity.getUuid() + split + fileEntity.getState()
                        + split + fileEntity.getFileName();
                fileEntity.setDeleteFlag("Y");
                fileService.save(fileEntity);
                File localFile = new File(path);
                localFile.delete();
            }
            finance.setDeleteFlag(pageData.get("deleteFlag").toString());
        }
        financeService.save(finance);
        return null;
    }

//    @RequestMapping(value = "/finance-ins-upd-del")
//    public Object financeInsUpdDel(){
//        PageData pageData = this.getPageData();
//        SystemUserEntity systemUserEntity = JsonUtils.jsonToObject(this.getRequest().getSession().getAttribute(ConsoleConstant.SESSIONUSER).toString(),SystemUserEntity.class);
//        if(null!=pageData.get("info")&&!"".equals(pageData.get("info").toString())){
//            FinanceEntity financeEntity = null;
//            String info = pageData.get("info").toString();
//            PageData entity = JsonUtils.jsonToObject(info, PageData.class);
//            Integer id = -1;
//            //修改
//            if(null!=entity.get("id")&&!"".equals(entity.get("id").toString())){
//                id = Integer.valueOf(entity.get("id").toString());
//            }
//            financeEntity = financeService.findById(id);
//
//            financeEntity.setAssignMoney(entity.get("assignMoney").toString());
//            financeEntity.setAssignTime(entity.get("assignTime").toString());
//            if(null!=entity.get("proID")&&!"".equals(entity.get("proID").toString())){
//                financeEntity.setProID(Integer.valueOf(entity.get("proID").toString()));
//            }
//            financeEntity.setUserId(systemUserEntity.getId());
//            financeEntity.setBelongTo(systemUserEntity.getBelongTo());
//            financeService.save(financeEntity);
//        }
//        if(null!=pageData.get("id")&&!"".equals(pageData.get("id").toString())&&null!=pageData.get("deleteflag")&&!"".equals(pageData.get("deleteflag").toString())){
//            FinanceEntity financeEntity = financeService.findById(Integer.valueOf(pageData.get("id").toString()));
//            financeEntity.setDeleteFlag("Y");
//            financeService.save(financeEntity);
//        }
//        return null;
//    }

	@RequestMapping("/finance-download")
    public void export(HttpServletResponse response){
        PageData param = new PageData();
        param.put("deleteFlag", InsUpdDelFlagConstant.DELETE_FLAG_N);
        List<FinanceEntity> entitys = financeService.findAll(param);
        List<FinanceEntityExcel> excelEntities = new ArrayList<>();
        for(FinanceEntity tempEntity :entitys){            
            FinanceEntityExcel excel = new CopyObjectEntity2EntityExcel<FinanceEntityExcel, FinanceEntity>().copy(FinanceEntityExcel.class,FinanceEntity.class,tempEntity);
            excelEntities.add(excel);
        }
        EasyPoiUtil.exportExcel(excelEntities,"","",FinanceEntityExcel.class, DateUtil.getID()+".xls",response);
    }


    @RequestMapping("/project-finance-count/{id}")
    public long projectMeetCount(@PathVariable("id") Integer id){
        PageData pd = new PageData();
        pd.put("deleteFlag", "N");
        pd.put("proID", id);
        return financeService.count(pd);
    }

}